#!/bin/bash

source /usr/local/etc/library.sh

set -e

[[ "$1" == "stop" ]] && {
  echo "stopping Cron..."
  killall cron
  echo "stopping Redis..."
  killall redis-server
  echo "stopping Postfix..."
  postfix stop
  echo "stopping logs..."
  killall tail
  exit 0
}

# we want to work in the volume version of the code
rm /var/www/nextcloud
ln -s /data/nextcloud /var/www/nextcloud

echo "Starting Redis"
sed -i 's|^requirepass .*|requirepass default|' /etc/redis/redis.conf
chown redis:redis /etc/redis/redis.conf
mkdir -p /var/run/redis
chown redis /var/run/redis
sudo -u redis redis-server /etc/redis/redis.conf

echo "Starting Cron"
cron

echo "Starting Postfix"
postfix start

# INIT DATABASE AND NEXTCLOUD CONFIG (first run)
test -f /data/nextcloud/config/config.php || {
  echo "Uninitialized instance, running nc-init..."
  source /usr/local/etc/library.sh
  run_app_unsafe /nc-init.sh
  mv /index.php /var/www/nextcloud/    # restore this file after init
}

# Better do real provisioning at the end, as it can restart PHP asynchronously
sed -i "s|'password'.*|'password' => 'default',|"        /data/nextcloud/config/config.php
sed -i "s|'dbpassword' =>.*|'dbpassword' => 'default',|" /data/nextcloud/config/config.php
echo -e "[client]\npassword=default" > /root/.my.cnf
chmod 600 /root/.my.cnf
DBPASSWD=default
DBADMIN=ncadmin
mysql <<EOF
GRANT USAGE ON *.* TO '$DBADMIN'@'localhost' IDENTIFIED BY '$DBPASSWD';
DROP USER '$DBADMIN'@'localhost';
CREATE USER '$DBADMIN'@'localhost' IDENTIFIED BY '$DBPASSWD';
GRANT ALL PRIVILEGES ON nextcloud.* TO $DBADMIN@localhost;
FLUSH PRIVILEGES;
EXIT
EOF

# Trusted Domain ( local IP )
IFACE=$( ip r | grep "default via" | awk '{ print $5 }' | head -1 )
IP=$( ip a show dev "$IFACE" | grep global | grep -oP '\d{1,3}(.\d{1,3}){3}' | head -1 )
ncc config:system:set trusted_domains 1 --value="$IP"

# Trusted Domain ( as an argument )
[[ "$2" != "" ]] && \
  ncc config:system:set trusted_domains 6 --value="$2"

echo "Provisioning"
bash /usr/local/bin/ncp-provisioning.sh

# Display NC logs in the docker logs
tail -f -n0 /data/nextcloud/data/nextcloud.log &

exit 0
